package com.cqvip.generator.service;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.builder.Controller;
import com.baomidou.mybatisplus.generator.config.builder.Entity;
import com.baomidou.mybatisplus.generator.config.builder.GeneratorBuilder;
import com.baomidou.mybatisplus.generator.config.builder.Service;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.cqvip.generator.constant.GeneratorParamModel;
import com.cqvip.innocence.project.controller.AbstractController;
import com.cqvip.innocence.project.model.entity.base.BaseModel;
import org.apache.commons.lang3.StringUtils;

import java.util.Scanner;

/**
 * 代码生成器工厂抽象类
 *
 * @author Innocence
 * @date 2020/10/28
 */
public class GeneratorService {

    /**
     * 读取控制台内容
     *
     * @param tip
     * @return
     */
    protected String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + "：");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotEmpty(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "！");
    }

    /**
     * 全局配置
     *
     * @return com.baomidou.mybatisplus.generator.config.GlobalConfig
     * @author Innocence
     * @date 2021/1/4
     */
    protected GlobalConfig setGlobal(GeneratorParamModel model) {
        GlobalConfig.Builder builder = GeneratorBuilder.globalConfigBuilder();
        //是否重写生成的文件，默认为false，这里指定后改为true
//        builder.fileOverride();
        builder.outputDir(System.getProperty("user.dir") + "/src/main/java");
        builder.author(model.getAuthor());
        //开启Swagger注解
        builder.enableSwagger();
        return builder.build();
    }

    /**
     * 全局数据配置
     *
     * @return com.baomidou.mybatisplus.generator.config.DataSourceConfig
     * @author Innocence
     * @date 2021/1/4
     */
    protected DataSourceConfig setDataSource(GeneratorParamModel model) {
        DataSourceConfig.Builder builder = new DataSourceConfig.Builder(
                model.getDataSourceUrl(),
                model.getDataSourceUserName(),
                model.getDataSourcePassword()
        );
        if (StrUtil.isNotBlank(model.getSchemaName())) {
            builder.schema(model.getSchemaName());
        }
        builder.dbQuery(model.getDbQuery());
        return builder.build();
    }

    /**
     * 全局策略配置
     *
     * @return com.baomidou.mybatisplus.generator.config.StrategyConfig
     * @author Innocence
     * @date 2021/1/4
     */
    protected StrategyConfig setStrategy(GeneratorParamModel model) {
        StrategyConfig.Builder builder = new StrategyConfig.Builder();
        builder.addInclude(scanner("表名，多个英文逗号分割").split(","));

        builder.enableCapitalMode();
        //实体策略配置
        Entity.Builder entityBuilder = builder.entityBuilder();
        entityBuilder.naming(NamingStrategy.underline_to_camel);
        entityBuilder.superClass(BaseModel.class);
        entityBuilder.enableLombok();
        entityBuilder.enableSerialVersionUID();
        entityBuilder.enableChainModel();
        entityBuilder.enableTableFieldAnnotation();
        entityBuilder.columnNaming(NamingStrategy.underline_to_camel);
        entityBuilder.addSuperEntityColumns(model.getSuperEntityColumns());
        //Controller策略配置
        Controller.Builder controllerBuilder = builder.controllerBuilder();
        controllerBuilder.superClass(AbstractController.class);
        controllerBuilder.enableRestStyle();
        controllerBuilder.enableHyphenStyle();
        //Service策略配置
        Service.Builder serviceBuilder = builder.serviceBuilder();
        serviceBuilder.convertServiceFileName(entityName -> entityName + "Service");
        return builder.build();
    }

    /**
     * 全局包配置
     *
     * @return com.baomidou.mybatisplus.generator.config.PackageConfig
     * @author Innocence
     * @date 2021/1/4
     */
    protected PackageConfig setPackage(GeneratorParamModel model) {
        PackageConfig.Builder builder = new PackageConfig.Builder();
        //模块名
        builder.moduleName(model.getModuleName());
        //包名
        builder.parent(model.getParent());
        builder.entity(model.getEntity());
        return builder.build();
    }

    /**
     * 全局自定义配置
     *
     * @return com.baomidou.mybatisplus.generator.InjectionConfig
     * 如果模板引擎是 freemarker
     * String templatePath = "/templates/mapper.xml.ftl";
     * 如果模板引擎是 velocity
     * String templatePath = "/templates/mapper.xml.vm";
     * @author Innocence
     * @date 2021/1/4
     */
    protected InjectionConfig setInjection() {
        return new InjectionConfig.Builder().build();
    }

    /**
     * 全局模板配置
     *
     * @return com.baomidou.mybatisplus.generator.config.TemplateConfig
     * @author Innocence
     * @date 2021/1/4
     */
    protected TemplateConfig setTemplate() {
        return new TemplateConfig.Builder().build();
    }

    /**
     * 代码生成器主要方法，子类根据不同的数据库构造GeneratorParamModel执行该方法
     *
     * @param model
     * @return void
     * @author Innocence
     * @date 2022/4/1
     */
    public void generator(GeneratorParamModel model) {
        AutoGenerator autoGenerator = new AutoGenerator(setDataSource(model));
        autoGenerator.global(setGlobal(model));
        autoGenerator.packageInfo(setPackage(model));
        autoGenerator.strategy(setStrategy(model));
        autoGenerator.template(setTemplate());
        autoGenerator.injection(setInjection());
        autoGenerator.execute();
    }
}
